package com.sgu6.sgu6_machine.ui.dialog;

import android.app.Dialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.viewpager2.widget.ViewPager2;

import com.sgu6.middleware.util.HexUtil;
import com.sgu6.serialport.manager.SerialPortManagerForCard;
import com.sgu6.sgu6_machine.R;
import com.sgu6.sgu6_machine.adapter.MemberFragmentPagerAdapter;
import com.sgu6.sgu6_machine.container.MachineContainer;
import com.sgu6.sgu6_machine.dto.MemberCardInfoDto;
import com.sgu6.sgu6_machine.event.ReadCardEvent;
import com.sgu6.sgu6_machine.event.RechargeEvent;
import com.sgu6.sgu6_machine.presenter.MachineP;
import com.sgu6.sgu6_machine.ui.dialog.proxy.ProxyDialogFragment;
import com.sgu6.sgu6_machine.ui.fragment.dialog.MemberQueryF;
import com.sgu6.sgu6_machine.ui.fragment.dialog.MemberRechargeF;
import com.sgu6.sgu6_machine.ui.views.indicator.RectIndicator;
import com.sgu6.sgu6_machine.listener.OnDiaDismissListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class RechargeDialogF extends ProxyDialogFragment implements TextWatcher,DialogInterface.OnDismissListener {


    @BindView(R.id.label)
    TextView label;
    @BindView(R.id.etCard)
    EditText etCard;
    @BindView(R.id.view_pager2)
    ViewPager2 viewPager2;
    @BindView(R.id.stadium_indicator)
    RectIndicator stadiumIndicator;

    private MemberFragmentPagerAdapter adapter;
    private List<Fragment> fragments = new ArrayList<>();
    private CountDownTimer timer;
    private boolean isReadCard = true;
    private MachineP mp = new MachineP();
    private Fragment memberQueryF, memberRechargeF;
    public Dialog dLog ;


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
        getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        View v = inflater.inflate(R.layout.dialog_fragment_recharge, container, false);
        unbinder = ButterKnife.bind(this, v);

        initTimer();

        initData();

        initUI();

        return v;
    }

    private void initData() {
        memberQueryF = new MemberQueryF();
        memberRechargeF = new MemberRechargeF();
        fragments.add(memberQueryF);
        fragments.add(memberRechargeF);
    }

    private void initTimer() {
        String key = "";
        if (MachineContainer.machineInfo != null && MachineContainer.machineInfo.getMerchantId() != null && MachineContainer.machineInfo.getMerchantId().length() > 12) {
            key = MachineContainer.machineInfo.getMerchantId().substring(0, 12);
        }
        String finalKey = key;
        timer = new CountDownTimer(60 * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                int second = (int) (millisUntilFinished / 1000);
                if (isReadCard) {
                    SerialPortManagerForCard.getInstance().sendBytes(HexUtil.HexString2Bytes("AA080400FFFFFFFFFFFF"));
                }
            }

            @Override
            public void onFinish() {
                timer.cancel();
                dismiss();
                timer = null;
            }
        }.start();
    }


    private void initUI() {
        etCard.addTextChangedListener(this);
        adapter = new MemberFragmentPagerAdapter(getActivity(), fragments);
        viewPager2.setAdapter(adapter);
        viewPager2.setOffscreenPageLimit(1);
        stadiumIndicator.setWithViewPager2(viewPager2);
    }


    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
        dLog = getDialog();

        if (dLog != null) {
            DisplayMetrics dm = new DisplayMetrics();
            requireActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
            dLog.getWindow().setLayout((int) (dm.widthPixels * 0.6), ViewGroup.LayoutParams.WRAP_CONTENT);
            dLog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    if (timer != null) {
                        timer.cancel();
                        timer = null;
                    }
                    memberQueryF = null;
                    memberRechargeF = null;
                    onDestroy();
                    onDestroyView();
                    onDetach();
                    Runtime.getRuntime().gc();
                }
            });
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "onDestroy: ");
    }

    @Override
    public void onDetach() {
        super.onDetach();
        Log.i(TAG, "onDetach: ");
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        Log.i(TAG, "onDestroyView: ");
        EventBus.getDefault().unregister(this);
        unbinder.unbind();
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

    public void goRecharge() {
        viewPager2.setCurrentItem(1);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRechargeEvent(RechargeEvent event) {
        goRecharge();
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onReadCardEvent(ReadCardEvent event) {
        if (event.cmd.startsWith("AA120400")) {

            String sgu6_code = event.cmd.substring(8);

            SerialPortManagerForCard.getInstance().sendBytes(HexUtil.HexString2Bytes("AA03B20501"));

            isReadCard = false;

            mp.getMemberCardInfo(sgu6_code);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMemberCardInfoEvent(MemberCardInfoDto memberCardInfoDto) {
        etCard.setText(memberCardInfoDto.getCardCode());
        etCard.setSelection(memberCardInfoDto.getCardCode().length());
        Log.i(TAG, "onMemberCardInfoEvent: ");
    }

    @Override
    public void onPause() {
        super.onPause();
        Log.i(TAG, "onPause: ");
    }

    @Override
    public void onStop() {
        super.onStop();
        Log.i(TAG, "onStop: ");
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        super.onDismiss(dialog);
        Log.i(TAG, "onDismiss: ");
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }



    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        ((MemberRechargeF) memberRechargeF).updateCardNo(s.toString());
        ((MemberQueryF) memberQueryF).updateCardNo(s.toString());
    }

    @Override
    public void show(@NonNull FragmentManager manager, @Nullable String tag) {
        try {
            //在每个add事务前增加一个remove事务，防止连续的add
            manager.beginTransaction().remove(this).commitAllowingStateLoss();
            super.show(manager, tag);
        } catch (Exception e) {
            Log.i(TAG, "show: " + e.getLocalizedMessage());
            //同一实例使用不同的tag会异常,这里捕获一下
            e.printStackTrace();
        }
    }
}
